#include "ota_api.h"
#include "user_extern.h"
extern EventGroupHandle_t wifi_event_group;

static const int CONNECTED_BIT = BIT0;
static const char *TAG = "DIGI OTA";
esp_err_t _http_event_handler(esp_http_client_event_t *evt)
{
    switch (evt->event_id)
    {
    case HTTP_EVENT_ERROR:
        ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
        break;
    case HTTP_EVENT_ON_CONNECTED:
        ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
        break;
    case HTTP_EVENT_HEADER_SENT:
        ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
        break;
    case HTTP_EVENT_ON_HEADER:
        ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
        break;
    case HTTP_EVENT_ON_DATA:
        ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
        break;
    case HTTP_EVENT_ON_FINISH:
        ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH");
        break;
    case HTTP_EVENT_DISCONNECTED:
        ESP_LOGD(TAG, "HTTP_EVENT_DISCONNECTED");
        break;
    }
    return ESP_OK;
}

#define CONFIG_FIRMWARE_UPGRADE_URL "http://192.168.4.3:8080/digimon.ota.bin"
void simple_ota_example_task(void *pvParameter)
{
    ESP_LOGI(TAG, "Starting DIGIMON OTA");

    xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
                        false, true, portMAX_DELAY);
    ESP_LOGI(TAG, "Connect to Wifi ! Start to Connect to Server....");

    esp_http_client_config_t config = {
        .url = CONFIG_FIRMWARE_UPGRADE_URL,
        .event_handler = _http_event_handler,
    };
    esp_err_t ret = esp_https_ota(&config);
    if (ret == ESP_OK)
    {
        printf("===================== RESTART ==========================\n");

        esp_restart();
    }
    else
    {
        ESP_LOGE(TAG, "Firmware Upgrades Failed");
        Dsystem.ota_status = 0;
        vTaskDelete(NULL);
    }
    while (0)
    {
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

int ota_init()
{
    xTaskCreate(&simple_ota_example_task, "ota_example_task", 8192, NULL, 5, NULL);
    return 0;
}